import { MpVO } from '@/services/MpService'
import { makeAutoObservable } from 'mobx'

class GlobalModel {
  /* ******************* 系统部分 ******************* */
  tenantId?: string
  userId?: string

  setUserId = (userId: string) => {
    this.userId = userId
  }
  setTenantId = (tenantId: string) => {
    this.tenantId = tenantId
  }
  /* ******************* 营销部分 ******************* */
  // 营销公众号
  defaultMp?: MpVO
  // 公众号列表
  mpList?: MpVO[]

  /**
   * 是否选择了默认公众号
   */
  get isSetDefaultMp() {
    return this.defaultMp !== undefined
  }

  /**
   * 是否授权了公众号
   */
  get isHasMp() {
    return this.mpList !== undefined && this.mpList.length > 0
  }

  get mpMenuList() {
    return this.mpList?.filter((mp) => mp.type === 'wx_mp').filter((mp) => mp.id !== this.defaultMp?.id) || []
  }

  /**
   * 设置公众号列表
   * @param mpList
   */
  setMpList(mpList: MpVO[]) {
    this.mpList = mpList
    this.setDefaultMp()
  }

  setDefaultMp(mp?: MpVO) {
    if (!this.isHasMp) return
    if (mp !== undefined) {
      this.defaultMp = mp
      window.localStorage.setItem('defaultMpId', mp.id.toString())
      return
    }

    let localDefaultMpId = window.localStorage.getItem('defaultMpId')
    mp = this.mpList?.find((item) => {
      return item.id.toString() === localDefaultMpId
    })
    this.defaultMp = mp
  }

  constructor() {
    makeAutoObservable(this, {}, { autoBind: true })
  }
}

export default GlobalModel
export const globalModel = new GlobalModel()
